package com.huxiu.yd.fragments;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.ChatActivity;
import com.huxiu.yd.R;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.Message;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.net.responses.MessageListResponse;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.AvatarView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class MessageListFragment extends Fragment implements
        PullToRefreshBase.OnRefreshListener2<ListView>, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private static final String ARG_MSG_TYPE = "msg_type";
    public static final int MSG_TYPE_PRIVATE = 0;
    public static final int MSG_TYPE_NOTIFICATION = 1;

    private int type;
    @InjectView(R.id.list)
    PullToRefreshListView list;

    @InjectView(R.id.empty)
    TextView emptyView;

    public static MessageListFragment newInstance(int type) {
        MessageListFragment fragment = new MessageListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_MSG_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    public MessageListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt(ARG_MSG_TYPE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.inject(this, view);
        adapter = new MyMessageAdapter();
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        list.setBackgroundColor(0xFFF9F9F9);
        list.setEmptyView(emptyView);
//        list.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        list.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
//        list.getRefreshableView().setSelector(new ColorDrawable(0xfff0f0f0));
//        list.getRefreshableView().setDrawSelectorOnTop(true);
        list.getRefreshableView().setDivider(getResources().getDrawable(R.drawable.cell_line));
        if (type == MSG_TYPE_PRIVATE) {
            list.setOnItemClickListener(this);
            list.getRefreshableView().setOnItemLongClickListener(this);
        }
        getItems(0);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        NetworkHelper.getInstance().getRequestQueue().cancelAll(this);
    }

    private int currentPage = 0;

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(currentPage + 1);
    }

    private List<Message> items = new ArrayList<>();

    MyMessageAdapter adapter;

    private void getItems(final int page) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        if (type == MSG_TYPE_PRIVATE)
            params.put("act", "get_private_list");
        else if (type == MSG_TYPE_NOTIFICATION)
            params.put("act", "system_msg");
        GsonRequest<MessageListResponse> request = new GsonRequest<>(url, Request.Method.POST,
                MessageListResponse.class, true, params,
                new Response.Listener<MessageListResponse>() {
                    @Override
                    public void onResponse(MessageListResponse response) {
                        if (response.isSuccess()) {
                            if (page == 0) {
                                items.clear();
                            }
                            Collections.addAll(items, response.data);
                            adapter.notifyDataSetChanged();
                            currentPage = response.page;
                        } else {
                            Utils.showToast(response.msg);
                        }
                        refreshComplete();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Throwable t = volleyError.getCause();
                if (t instanceof ErrorResponseException) {
                    String msg = volleyError.getMessage();
                    if (!"内容为空".equals(msg)) {
                        Utils.showToast(msg);
                    }
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
                refreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private void refreshComplete() {
        if (list != null)
            list.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (list != null)
                        list.onRefreshComplete();
                    if (adapter.getCount() == 0) {
                        if (type == MSG_TYPE_PRIVATE) {
                            emptyView.setText("您还没有收到任何私信哦~");
                        } else {
                            emptyView.setText("您还没有收到任何通知哦~");
                        }
                    }
                }
            }, 100);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (type == MSG_TYPE_PRIVATE) {
            Message msg = items.get(position - 1);
            Intent intent = new Intent(getActivity(), ChatActivity.class);
            intent.putExtra(ChatActivity.EXTRA_UID, msg.user_id);
            intent.putExtra(ChatActivity.EXTRA_NAME, msg.name);
            intent.putExtra(ChatActivity.EXTRA_AVATAR, msg.avatar);
            startActivity(intent);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (type == MSG_TYPE_PRIVATE) {
            final Message msg = items.get(position - 1);
            AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
            ab.setMessage(R.string.ask_delete_msg);
            ab.setNegativeButton(android.R.string.cancel, null);
            ab.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    deleteMsg(msg);
                }
            });
            ab.show();
        }
        return true;
    }

    void deleteMsg(final Message msg) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "del_dialogue");
//        params.put("other_user_id", msg.user_id);
        params.put("did", msg.did);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, true, params,
                new Response.Listener<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response) {
                        if (response.isSuccess()) {
                            items.remove(msg);
                            adapter.notifyDataSetChanged();
                            Utils.showToast(getString(R.string.del_msg_succ));
                        } else {
                            Utils.showToast(response.msg);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Throwable t = volleyError.getCause();
                if (t instanceof ErrorResponseException) {
                    Utils.showToast(volleyError.getMessage());
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private class MyMessageAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Message getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {

            Message msg = getItem(position);
            long id = 0;
            try {
                id = Long.parseLong(msg.did);
            } catch (Exception e) {
            }
            return id;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder vh;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.message_list_item, parent, false);
                vh = new ViewHolder(view);
                if (type == MSG_TYPE_PRIVATE)
                    vh.content.setSingleLine();
                else if (type == MSG_TYPE_NOTIFICATION)
                    vh.content.setSingleLine(false);
                view.setTag(vh);
            }
            final Message msg = getItem(position);
            vh = (ViewHolder) view.getTag();
            vh.avatar.setUserInfo(msg.user_id, msg.avatar, msg.name);
            vh.name.setText(msg.name);
            vh.time.setText(Utils.getDateString(msg.create_time));
            vh.content.setText(msg.content);

            return view;
        }


    }


    static class ViewHolder {
        @InjectView(R.id.avatar)
        AvatarView avatar;

        @InjectView(R.id.name)
        TextView name;

        @InjectView(R.id.time)
        TextView time;

        @InjectView(R.id.content)
        TextView content;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}
